package org.douxiaoban.client.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.mobclick.android.MobclickAgent;
import org.douxiaoban.client.R;
import org.douxiaoban.client.adapter.CollectionListAdapter;
import org.douxiaoban.client.api.CollectionRecord;
import org.douxiaoban.client.api.TestParcelable;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.model.BundleSerializable;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

/**
 * Created by IntelliJ IDEA.
 * User: huangzhongkun
 * Date: 11-6-5
 * Time: 下午11:34
 */
public class CollectionMusicListActivity extends BaseActivity
        implements WorkspaceView.ScrollToScreenCallback{

    private ThreadTool _threadTool;
    private WorkspaceView _scrollView;
    private LayoutInflater _inflater;
    private CollectionMusicListActivity _this;

    private LinearLayout _book_progressLay;
    private TitleStyle _title_style;
    private PopupRecommend _popup_recommend;

    //wish
    private ListView _book_wish_listview;
    private CollectionListAdapter _book_wish_adapter;
    private int _book_wish_page = 1;
    private Boolean _book_wish_is_loading_more = false;
    private Boolean _book_wish_is_no_more = false;
    private View _book_foot_view;

    //reading
    private ListView _book_reading_listview;
    private CollectionListAdapter _book_reading_adapter;
    private int _book_reading_page = 1;
    private Boolean _book_reading_is_loading_more = false;
    private Boolean _book_reading_is_no_more = false;

    //readed
    private ListView _book_readed_listview;
    private CollectionListAdapter _book_readed_adapter;
    private int _book_readed_page = 1;
    private Boolean _book_readed_is_loading_more = false;
    private Boolean _book_readed_is_no_more = false;

    private String _curent_user_id;
    private View viewWishList ;
    private View viewReadingList;
    private View viewReadedList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         _this = this;
        _scrollView = new WorkspaceView(this, null);
        _scrollView.setTouchSlop(32);

         _inflater =
                (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        _curent_user_id =  getIntent().getStringExtra(Assistant.KEY_USER_ID);
        if(_curent_user_id==null || _curent_user_id.equals(""))
            _curent_user_id = App.userId;

        resignViewCompent();
        startThreadDownloadData(Assistant.STATUS_MUSIC_LISTENED,_book_readed_page);
        resignScrollListener();
        _scrollView.setScrollToScreenCallback(this);


        //custom title
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        this.setContentView(_scrollView);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

        _popup_recommend = new PopupRecommend(this);
        _title_style = new TitleStyle(this);
        _title_style.initTitleStyle();
        _title_style.initPageController(3,1);

    }

    private void resignViewCompent(){
             viewWishList = _inflater.inflate(R.layout.collection_list,null);
             viewReadingList = _inflater.inflate(R.layout.collection_list,null);
             viewReadedList = _inflater.inflate(R.layout.collection_list,null);

           _book_progressLay = (LinearLayout)viewWishList.findViewById(R.id.collection_progress);
           _book_foot_view = _inflater.inflate(R.layout.list_view_foot,null);

           //wish
           _book_wish_listview = (ListView)viewWishList.findViewById(R.id.book_listview);
           _book_wish_listview.addFooterView(_book_foot_view);
            _book_wish_adapter = new CollectionListAdapter(this,
                   _handler,Assistant.STATUS_BOOK_WISH,_book_wish_listview);
           _book_wish_listview.setAdapter(_book_wish_adapter);

           //reading

           _book_reading_listview = (ListView)viewReadingList.findViewById(R.id.book_listview);
           _book_reading_listview.addFooterView(_book_foot_view);
            _book_reading_adapter = new CollectionListAdapter(this,
                   _handler,Assistant.STATUS_BOOK_READING,_book_reading_listview);
           _book_reading_listview.setAdapter(_book_reading_adapter);

           //readed
           _book_readed_listview = (ListView)viewReadedList.findViewById(R.id.book_listview);
           _book_readed_listview.addFooterView(_book_foot_view);
            _book_readed_adapter = new CollectionListAdapter(this,
                   _handler,Assistant.STATUS_BOOK_READED,_book_readed_listview);
           _book_readed_listview.setAdapter(_book_readed_adapter);

           _threadTool = ThreadTool.instace(this);

           _scrollView.addView(viewReadedList);
           _scrollView.addView(viewReadingList);
           _scrollView.addView(viewWishList);
       }

       private void resignScrollListener(){
           _book_readed_listview.setOnItemClickListener(
                                       new AbsListView.OnItemClickListener(){
               @Override
               public void onItemClick(AdapterView<?> adapterView,
                                       View view, int position, long l) {

                   /**
                    * 传入subject 的id,分类,与subject record对象到内容页
                    */
                   Intent intent = new Intent(CollectionMusicListActivity.this,
                           CollectionSubjectActivity.class);

                   intent.putExtra(Assistant.KEY_OF_INTENT_ID,
                           _book_readed_adapter._crs.get(position).id);
                   intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,
                           Assistant.STATUS_MUSIC);

                   CollectionRecord record = _book_readed_adapter._crs.get(position);

                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,record.rating);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,record.status);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY,record.summary);
                   TestParcelable testParcelable = new TestParcelable();
                   //intent.putExtra("parcelable",testParcelable);
                   intent.putExtra("parcelable",_book_readed_adapter._crs.get(position));
                   _this.startActivity(intent);
               }
           });

           _book_reading_listview.setOnItemClickListener(
                   new AbsListView.OnItemClickListener(){
                         @Override
               public void onItemClick(AdapterView<?> adapterView,
                                       View view, int position, long l) {

                   /**
                    * 传入subject 的id,分类,与subject record对象到内容页
                    */
                   Intent intent = new Intent(CollectionMusicListActivity.this,
                           CollectionSubjectActivity.class);

                   intent.putExtra(Assistant.KEY_OF_INTENT_ID,
                           _book_reading_adapter._crs.get(position).id);
                   intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,
                           Assistant.STATUS_MUSIC);

                   CollectionRecord record = _book_reading_adapter._crs.get(position);

                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,record.rating);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,record.status);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY,record.summary);

                   _this.startActivity(intent);
               }
                   }
           );

           _book_wish_listview.setOnItemClickListener(new AbsListView.OnItemClickListener(){
                        @Override
               public void onItemClick(AdapterView<?> adapterView,
                                       View view, int position, long l) {

                   /**
                    * 传入subject 的id,分类,与subject record对象到内容页
                    */
                   Intent intent = new Intent(CollectionMusicListActivity.this,
                           CollectionSubjectActivity.class);

                   intent.putExtra(Assistant.KEY_OF_INTENT_ID,
                           _book_wish_adapter._crs.get(position).id);
                   intent.putExtra(Assistant.KEY_OF_INTENT_CATEGORY,
                           Assistant.STATUS_MUSIC);

                   CollectionRecord record = _book_wish_adapter._crs.get(position);

                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_RATTING,record.rating);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_TYPE,record.status);
                   intent.putExtra(Assistant.KEY_OF_MY_SUBJECT_SUMMARY,record.summary);

                   _this.startActivity(intent);
               }
           });

            _book_wish_listview.setOnScrollListener(new AbsListView.OnScrollListener(){
               @Override
               public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                    if(firstVisibleItem > 0 && (totalItemCount-firstVisibleItem)<7
                       && !_book_wish_is_no_more && !_book_wish_is_loading_more){
                       _book_wish_page += 15;
                       _book_wish_is_loading_more = true;
                       startThreadDownloadData(Assistant.STATUS_BOOK_WISH,_book_wish_page);
                   }
               }
               @Override
               public void onScrollStateChanged(AbsListView absListView, int i) {

               }
           });

           _book_reading_listview.setOnScrollListener(new AbsListView.OnScrollListener(){
               @Override
               public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                    if(firstVisibleItem > 0 && (totalItemCount-firstVisibleItem)<7
                       && !_book_reading_is_no_more && !_book_reading_is_loading_more){
                       _book_reading_page += 15;
                       _book_reading_is_loading_more = true;
                       startThreadDownloadData(Assistant.STATUS_BOOK_READING,
                                                               _book_reading_page);
                   }
               }
               @Override
               public void onScrollStateChanged(AbsListView absListView, int i) {

               }
           });

           _book_readed_listview.setOnScrollListener(new AbsListView.OnScrollListener(){
               @Override
               public void onScroll(AbsListView view, int firstVisibleItem,
                                    int visibleItemCount, int totalItemCount) {
                    if(firstVisibleItem > 0 && (totalItemCount-firstVisibleItem)<7
                       && !_book_readed_is_no_more && !_book_readed_is_loading_more){
                       _book_readed_page += 15;
                       _book_readed_is_loading_more = true;
                       startThreadDownloadData(Assistant.STATUS_BOOK_READED,_book_readed_page);
                   }
               }
               @Override
               public void onScrollStateChanged(AbsListView absListView, int i) {

               }
           });
        }

       private void startThreadDownloadData(String bookType,int page){
           //TODO: This is test data
            String category = "music";

           _threadTool.startThreadFetchUserCollection(_curent_user_id,category,page,
                   bookType,_handler);
        }

       public void startThreadImageDownload(int position,String url,String bookType){
          _threadTool.startThreadImageDownload(bookType,url,_handler,position);
       }

       private Handler _handler = new Handler() {
           @Override
           public void handleMessage(Message msg) {
               switch (msg.what){
                   case Assistant.FETCH_BOOK_READED_DONE:
                       Bundle bundle = msg.getData();
                       BundleSerializable ser = (BundleSerializable)
                               bundle.getSerializable(Assistant.KEY_OF_COLLECTION);
                       System.out.println(ser.crs);

                       //无更多的数据加载，删除footview，
                       if(ser.crs == null || ser.crs.size()<Assistant.PAGE_SIZE){
                           _book_readed_is_no_more = true;
                           _book_readed_listview.removeFooterView(_book_foot_view);
                           //TODO 告诉用户，已经加载到底了
                       }

                       if(_book_readed_adapter._crs == null)
                           _book_readed_adapter._crs = ser.crs;
                       else
                           _book_readed_adapter._crs.addAll(ser.crs);

                       //update title
                      if(_book_readed_adapter!=null && _book_readed_adapter._crs.size()>0){
                        _title_style.setTitle(_book_readed_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listened));
                        }else{
                        _title_style.setTitle(getString(R.string.title_listened));
                        }

                       _book_readed_adapter.changeData();

                       _book_readed_listview.setVisibility(View.VISIBLE);
                       viewReadedList.findViewById(R.id.collection_progress).setVisibility(View.GONE);

                       _book_readed_is_loading_more = false;
                        break;
                   case Assistant.FETCH_BOOK_READING_DONE:
                         Bundle bl = msg.getData();
                       BundleSerializable se = (BundleSerializable)
                               bl.getSerializable(Assistant.KEY_OF_COLLECTION);
                       System.out.println(se.crs);

                       //无更多的数据加载，删除footview，
                       if(se.crs == null || se.crs.size()<Assistant.PAGE_SIZE){
                           _book_reading_is_no_more = true;
                           _book_reading_listview.removeFooterView(_book_foot_view);
                           //TODO 告诉用户，已经加载到底了
                       }

                       if(_book_reading_adapter._crs == null)
                           _book_reading_adapter._crs = se.crs;
                       else
                           _book_reading_adapter._crs.addAll(se.crs);

                       //update title
                      if(_book_reading_adapter!=null && _book_reading_adapter._crs.size()>0){
                            _title_style.setTitle(_book_reading_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listening));
                      }else{
                         _title_style.setTitle(getString(R.string.title_listening));
                        }

                       _book_reading_adapter.changeData();

                       _book_reading_listview.setVisibility(View.VISIBLE);
                       viewReadingList.findViewById(R.id.collection_progress).setVisibility(View.GONE);

                       _book_reading_is_loading_more = false;
                       break;
                   case Assistant.FETCH_BOOK_WISH_DONE:
                          Bundle blw = msg.getData();
                       BundleSerializable sew = (BundleSerializable)
                               blw.getSerializable(Assistant.KEY_OF_COLLECTION);

                       //无更多的数据加载，删除footview，
                       if(sew.crs == null || sew.crs.size()<Assistant.PAGE_SIZE){
                           _book_wish_is_no_more = true;
                           _book_wish_listview.removeFooterView(_book_foot_view);
                           //TODO 告诉用户，已经加载到底了
                       }

                       if(_book_wish_adapter._crs == null)
                           _book_wish_adapter._crs = sew.crs;
                       else
                           _book_wish_adapter._crs.addAll(sew.crs);

                      if(_book_wish_adapter!=null && _book_wish_adapter._crs.size()>0){
                            _title_style.setTitle(_book_wish_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listen_wish));
                        }else{
                        _title_style.setTitle(getString(R.string.title_listen_wish));
                    }

                       _book_wish_adapter.changeData();

                       _book_wish_listview.setVisibility(View.VISIBLE);
                        viewWishList.findViewById(R.id.collection_progress).setVisibility(View.GONE);

                       _book_wish_is_loading_more = false;
                       break;
                   case Assistant.FETCH_COLLECTION_FAIL:
                       _popup_recommend.showToastWindow(0,getString(R.string.load_fail));
                        finish();
                       //_book_is_loading_more = false;
                        break;
                    case Assistant.FETCH_BOOK_READED_IMAGE_DONE:
                       Bundle be = msg.getData();
                       ThreadTool.ImageSerialz is = (ThreadTool.ImageSerialz)
                               be.getSerializable(Assistant.THREAD_IMAGE_KEY);
                       _book_readed_adapter._crs.get(is.m_iPosition).icon_bitmap = is.m_bitmap;

                       _book_readed_adapter.notifyDataSetChanged();
                       break;
                    case Assistant.FETCH_BOOK_WISH_IMAGE_DONE:
                            Bundle bew = msg.getData();
                       ThreadTool.ImageSerialz isw = (ThreadTool.ImageSerialz)
                               bew.getSerializable(Assistant.THREAD_IMAGE_KEY);
                       _book_wish_adapter._crs.get(isw.m_iPosition).icon_bitmap = isw.m_bitmap;

                       _book_wish_adapter.notifyDataSetChanged();
                        break;
                    case Assistant.FETCH_BOOK_READING_IMAGE_DONE:
                        Bundle beg = msg.getData();
                       ThreadTool.ImageSerialz isg = (ThreadTool.ImageSerialz)
                               beg.getSerializable(Assistant.THREAD_IMAGE_KEY);
                       _book_reading_adapter._crs.get(isg.m_iPosition).icon_bitmap = isg.m_bitmap;

                       _book_reading_adapter.notifyDataSetChanged();
                        break;
                   case Assistant.FETCH_IMAGE_FAIL:
                       break;
                   default:
                       break;
               }
             //  super.handleMessage(msg);
           }
       };

       @Override
       public void callback(int currentIndex) {

           switch (currentIndex){
               case Assistant.BOOK_INDEX_READED:
                   if(_book_readed_adapter!=null && _book_readed_adapter._crs.size()>0){
                     _title_style.setTitle(_book_readed_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listened));
                   }else{
                     _title_style.setTitle(getString(R.string.title_listened));
                   }

                   _title_style.setCurrentPage(1);

                   break;
               case Assistant.BOOK_INDEX_READING:
                   if(!_book_reading_is_loading_more && _book_reading_adapter._crs.size() == 0)
                    startThreadDownloadData(Assistant.STATUS_MUSIC_LINSTENING,_book_reading_page);

                   if(_book_reading_adapter!=null && _book_reading_adapter._crs.size()>0){
                     _title_style.setTitle(_book_reading_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listening));
                   }else{
                     _title_style.setTitle(getString(R.string.title_listening));
                   }
                   _title_style.setCurrentPage(2);

                   break;
               case Assistant.BOOK_INDEX_WISH:
                   if(!_book_readed_is_loading_more && _book_wish_adapter._crs.size() == 0)
                   startThreadDownloadData(Assistant.STATUS_MUSIC_WISH,_book_wish_page);

                    if(_book_wish_adapter!=null && _book_wish_adapter._crs.size()>0){
                     _title_style.setTitle(_book_wish_adapter._crs.get(0).total_result+
                           getString(R.string.zhang)+getString(R.string.title_listen_wish));
                   }else{
                     _title_style.setTitle(getString(R.string.title_listen_wish));
                   }
                   _title_style.setCurrentPage(3);
                   break;
               default:
                   break;
           }
       }

      @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }
}